<template>
  <view class="page container">
    <scroll-view scroll-y="true" style="max-height: 80vh;">
    	<u-form
    	  :model="basicForm"
    	  :rules="rules"
    	  labelPosition="top"
    	  ref="form"
    	  labelWidth="auto"
    	  :labelStyle="{
    	  	fontSize: '14px',
    	  	color: '#B2B2B2',
    	  	lineHight: '20px'
    	  }"
    	>
    	  <view class="basic-style">
					<u-form-item label="款项类型" required prop="contractPaymentType" v-if="basicForm.contractPaymentType && (basicForm.contractPaymentType == 'quality' || basicForm.contractPaymentType == 'bail')">
						<h-dict-select
							disabled
							style="width: 100%" 
							v-model="basicForm.contractPaymentType" 
							placeholder="请选择款项类型"
							dictName="contract_payment_type">
						</h-dict-select>
					</u-form-item>
					<u-form-item label="款项类型" prop="contractPaymentType" v-else required>
						<h-dict-select
							style="width: 100%" 
							v-model="basicForm.contractPaymentType" 
							placeholder="请选择款项类型"
							:disabled="formDisabled"
							dictName="org_payment_type"
							@back="changeContractPaymentType">
						</h-dict-select>
					</u-form-item>
    	    <!-- <u-form-item label="款项名称" prop="kxmc" required>
    	      <u--input placeholder="请输入款项名称" disabled v-model="basicForm.kxmc" />
    	    </u-form-item> -->
    	    <u-form-item label="金额(元)" prop="je" required>
    	    <!-- <u--input type="number" placeholder="请输入金额" v-number-normal v-model="basicForm.je" @blur="onPlainFormMoneyBlur" /> -->
    				<h-number-input placeholder="请输入金额" :disabled="formDisabled" v-model="basicForm.je" :digit="2" :min="0" @blur="onPlainFormMoneyBlur"></h-number-input>
    	    </u-form-item>
    			<span v-if="basicForm.collectMoney || basicForm.invoicePaidAmount" style="color: red">
    				<span
							v-if="htlx == '1'">
							当前款项已收{{ basicForm.collectMoney }}元，已开票{{ basicForm.invoicePaidAmount }}元, 金额调整不可低于{{ totalAmount }}元
						</span>
    				<span v-if="htlx == '2'"> 当前款项已付{{basicForm.collectMoney}}元 , 金额调整不可低于实付金额</span>
    			</span>
    	    <u-form-item label="预计款项日期" prop="kxrq" required>
    	      <h-time-select
    	        mode="date"
    	        ref="remittanceDate"
    	        v-model="basicForm.kxrq"
    	        placeholder="请选择预计款项日期"
							:disabled="formDisabled || collectMoneyStatusDisabled"
    	        border="surround"
    	        suffixIcon="calendar-fill"
    	        :suffixIconStyle="{ color: '#B2B2B2' }"
    	      ></h-time-select>
    	    </u-form-item>
    	    <u-form-item label="款项节点说明" prop="kxjdsm" required>
    	      <u--input placeholder="请输入款项节点说明" :disabled="formDisabled || collectMoneyStatusDisabled" v-model="basicForm.kxjdsm" cursorSpacing="100"></u--input>
    	    </u-form-item>
    	  </view>
    		<view class="basic-style">
    		  <view class="basic-title basic-border">关联任务</view>
    		  <view class="space-y-1 py-1" v-if="basicForm.collectMoneyStatus != '已生成' && !formDisabled">
    		    <u-button size="small" type="primary" @click="addFormC" >新增</u-button>
    		  </view>
    		  <view v-for="(item, ind) in formDataC" :key="ind">
    		  	<planTaskFormInfo 
    		  		:item="item" 
    					:showKxxx="showKxxx"
    		  		:index="ind"
    					:collectMoneyStatus="basicForm.collectMoneyStatus"
    		  		@edit="handleEditFormC" 
    		  		@remove="handleRemoveFormC"
    		  		@copy="handleCopyFormC" 
    		  		:disabled="formDisabled"
    		  	/>
    		  </view>
    		  <u-popup mode="bottom" :show="showFormModalC" :closeOnClickOverlay="false">
    		    <planTaskForm ref="dataFormC" :index="ind" :projectId="projectId" :planId="basicForm.id" :totalPrice="basicForm.je" :collectMoneyStatus="basicForm.collectMoneyStatus" @submit="handleFormSubmitC" @close="closeFormModalC" />
    		  </u-popup>
    		</view>
    	  
    	</u-form>
    </scroll-view>
		<view class="space-x-1 mt-1" style="display: flex">
		  <u-button type="primary" text="保存" :loading="loading" @click="onSubmit" v-if="!formDisabled"></u-button>
		  <u-button type="primary" text="关闭" :loading="loading" @click="onClose"></u-button>
		</view>
  </view>
</template>

<script>
import planTaskForm from './planTaskForm.vue'
import planTaskFormInfo from './planTaskFormInfo.vue'
import Decimal from 'decimal.js'
export default {
  name: 'FormC',
	components: {
		planTaskForm,
		planTaskFormInfo
	},
  props: {
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
		// 禁用款项信息
    disablePayment: {
      type: Boolean,
      default: false,
      required: false,
    },
    datailDisabled: {
      type: Boolean,
      default: false,
    },
    index: {
      type: Number,
      default: null,
    },
		htlx: {
			type: [Number, String],
			default: null,
		},
		projectId: {
			type: [Number, String],
			default: null,
		},
		// 收付款计划列表数据
		dataSource: {
			type: [Array],
			default: ()=> [],
		},
  },
  data() {
    return {
			ind: null,
			showKxxx: false,
			teamId: '',
			companyId: '',
      loading: false,
			showFormModalC: false,
			formDataC: [], // 任务信息列表
      basicForm: {
        kxmc: '',
        je: '',
        kxrq: '',
        kxjdsm: '',
      },
			// 原始值
			defineBasicForm: {
			  kxmc: '',
			  je: '',
			  kxrq: '',
			  kxjdsm: '',
			},
      rules: {
        contractPaymentType: [{ required: true, message: '请选择款项类型!' }],
        kxmc: [{ required: true, message: '请输入款项名称!' }],
        je: [{ required: true, type:'number', pattern: /^-?(([0-9]*(\.[0-9]{1,3})$)|([0-9]+$))/, message: '请输入正确的金额!' }],
        kxrq: [{ required: true, message: '请选择预计款项日期!' }],
        kxjdsm: [{ required: true, message: '请输入款项节点说明!' }],
      },
    }
  },
	computed: {
		formDisabled() {
			return this.disabled
		},
		// 判断当为以应收时，需要禁用除金额外所有的字段
		collectMoneyStatusDisabled() {
			if (this.disabled) {
				return this.disabled
			} else {
				if (this.basicForm.collectMoneyStatus == '已生成') {
					return true
				} else {
					return this.disablePayment
				}
			}
		},
		// 计算金额最低填写
		totalAmount () {
			return Number(this.basicForm.collectMoney || 0) > Number(this.basicForm.invoicePaidAmount || 0) ? Number(this.basicForm.collectMoney || 0) : Number(this.basicForm.invoicePaidAmount || 0)
		}
	},
  methods: {
    reset() {
      this.$refs.form.resetFields()
    },
		
		addFormC() {
		  this.ind = null
			this.basicFormC = {}
		  this.showFormModalC = true
		},
		handleEditFormC([item, index]) {
		  this.basicFormC = { ...item }
		  this.ind = index
		  this.showFormModalC = true
			this.$nextTick(() => {
				this.openFormModalC()
			})
		},
		handleRemoveFormC(item) {
		  this.formDataC = this.formDataC.filter((i) => i !== item)
		},
		closeFormModalC() {
		  this.$refs.dataFormC.reset()
		  this.basicFormC = {}
		  this.ind = null
			this.showFormModalC = false
		},
		openFormModalC() {
		  this.$refs.dataFormC.basicForm = Object.assign({},this.basicFormC)
		},
		handleCopyFormC([item, index]) {
		  this.formDataC.push({
		    ...item,
		  })
		  this.$refs.uToast.show({
		  	message:'复制成功!'
		  })
		},
		/**
		 * 子表单新增点击确认
		 */
		handleFormSubmitC([data, index]) {
		  this.showFormModalC = false
		  if (typeof index === 'number') {
		    this.$set(this.formDataC, index, data)
		  } else {
		    this.formDataC.push(data)
		  }
		  // this.initBuyerInfo()
		},
    async onSubmit() {
      await this.$refs.form.validate()
			let count = this.dataSource.filter(item => item.contractPaymentType === this.basicForm.contractPaymentType).length;
			if (this.basicForm.contractPaymentType != 'progress' && count > 0) {
				// 判断是编辑还是新增
				if (this.basicForm.id) {
					// 编辑时需要根据原始值判断是否修改了款项类型
					if (this.defineBasicForm.contractPaymentType !== this.basicForm.contractPaymentType) {
						uni.showToast({
							title: `${this.basicForm.contractPaymentType_dictText}已存在！`,
							icon: 'none'
						})
						return
					}
				} else {
					// 当是新增时则直接提示
					uni.showToast({
						title: `${this.basicForm.contractPaymentType_dictText}已存在！`,
						icon: 'none'
					})
					return
				}
			}
			let planTaskList = await this.formDataC
			// 判断是否绑定任务
			if (Number(this.basicForm.je) != '0' && !planTaskList.length > 0) {
				uni.showToast({
					title: '请添加关联任务信息！',
					icon: 'none'
				})
				return
			}
			// 判断关联的任务id不能重复
			let taskIdList = await planTaskList.map(item => item.taskId)
			let taskIdListSet = new Set(taskIdList)
			if (taskIdList.length !== taskIdListSet.size) {
				uni.showToast({
					title: '关联任务不能重复！',
					icon: 'none'
				})
				return
			}
			// let totalRate = 0
			// planTaskList.forEach(item => {
			// 	totalRate= Number(item.paymentRate) + totalRate
			// })
			// if (totalRate !== 100) {
			// 	uni.showToast({
			// 		title: '关联任务款项分配占比需等于100%！',
			// 		icon: 'none'
			// 	})
			// 	return
			// }
			if(this.loading) return
			this.loading = true
			this.basicForm.planTaskList = await planTaskList
			this.basicForm.collectMoneyStatus = await this.basicForm.collectMoneyStatus?this.basicForm.collectMoneyStatus:'未生成'
			this.basicForm.taskId_dictText = await '' // 首先款项关联任务字段默认为空
			// 遍历planTaskList数组赋值给taskId_dictText
			this.basicForm.taskId_dictText = await planTaskList.map((obj)=>{return obj.categoryName }).join(",");
      if (!this.index) {
        this.$emit('submit', [{
          id: parseInt(Math.random() * 1000000000000),
          ...this.basicForm,
        }, this.index])
      } else {
        this.$emit('submit', [this.basicForm, this.index])
      }
    },
    onClose() {
			this.loading = false
      this.$emit('close')
    },
		// 选择款项类型
		changeContractPaymentType (val) {
			this.$set(this.basicForm, 'contractPaymentType_dictText', val.text)
			// 款项名称根据款项类型赋值且按照款项1-N排序
			// 判断dataSource数组对象中包含几个basicForm.contractPaymentType相同的对象，然后将其赋值给kxmc
			let count = this.dataSource.filter(item => item.contractPaymentType === val.value).length;
			this.basicForm.kxmc = val.text + (count + 1)
		},
		onPlainFormMoneyBlur () {
			if (this.basicForm.je === '' || this.basicForm.je === null || this.basicForm.je === undefined ) {
				let planTaskList = this.formDataC
				if (planTaskList && planTaskList.length > 0) {
					planTaskList.forEach(item => {
						let paymentRate = item.paymentRate
						item.paymentMoney = 0.00
					})
					this.formDataC = planTaskList
				}
			} else {
				let planTaskList = this.formDataC
				if (planTaskList && planTaskList.length > 0) {
					planTaskList.forEach(item => {
						// let paymentRate = item.paymentRate
						// item.paymentMoney = (this.basicForm.je * paymentRate / 100).toFixed(2)
						let paymentRate = item.paymentRate
						let amount = this.basicForm.je * paymentRate / 100
						item.paymentMoney = Math.round((amount + Number.EPSILON) * 100) / 100;
					})
					this.formDataC = planTaskList
				}
			}
			if (this.basicForm.collectMoney || this.basicForm.invoicePaidAmount) {
				if (this.basicForm.je === '') {
					return false
				}
				if (Number(this.basicForm.je) < this.totalAmount) {
					this.basicForm.je = this.totalAmount
				}
			}
		},
  }
}
</script>

<style scoped></style>
